import { createStore } from 'vuex'

const setLocalCartList = (state) => {
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}

const getLocalCartList = () => {
  try {
    return JSON.parse(localStorage.cartList)
  } catch {
    return {}
  }
}

export default createStore({
  state: {
    cartList: getLocalCartList()
  },
  mutations: {
    addItemToCart (state, payLoad) {
      const { shopId, productId, productInfo, num } = payLoad
      const shopInfo = state.cartList[shopId] || { shopName: '', productList: {} }
      let product = shopInfo.productList[productId]
      if (!product) {
        product = productInfo
        product.count = 0
      }
      product.count = product.count + num < 0 ? 0 : product.count + num;
      (num > 0) && (product.checked = true)
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    changeCartItemChecked (state, payLoad) {
      const { shopId, productId } = payLoad
      const product = state.cartList[shopId].productList[productId]
      product.checked = !product.checked
      setLocalCartList(state)
    },
    cleanCartProducts (state, shopId) {
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    },
    // 全选
    setCartItemChecked (state, shopId) {
      const product = state.cartList[shopId].productList
      if (product) {
        for (const i in product) {
          const products = product[i]
          products.checked = true
        }
      }
      setLocalCartList(state)
    },
    changeShopName (state, payLoad) {
      const { shopId, shopName } = payLoad
      const shopInfo = state.cartList[shopId] || { shopName: '', productList: {} }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    }
  },
  actions: {
  },
  modules: {
  }
})
